<template>
  <div class="allP">
  <ul>
    <li v-for="p in products">
      <router-link :to="{ name: 'detail',  params: { id: p.id }}">
        <img :src="p.src">
        <p>{{ p.title }}</p>
        <h2>{{ p.price | currency }}</h2>
      </router-link>
      <router-link :to="{ name: 'cart',  params: { id: p.id }}">
      <button
        :disabled="!p.inventory"
        @click="addToCart(p)">
        <span>加入购物车</span>
      </button>
      </router-link>
    </li>
  </ul>
  </div>

</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'ProductList',
  data () {
    return {
    }
  },
  computed: {
    // 使用对象展开运算符将 getters 混入 computed 对象中
    ...mapGetters({
      // 映射 this.products 为 store.getters.allProducts
      products: 'allProducts'
    })
  },
  methods: {
    // 使用对象展开运算符,将组件的 methods 映射为 store.dispatch 调用
    ...mapActions([
      // 映射 this.addToCart() 为 this.$store.dispatch('addToCart')
      'addToCart'
    ])
  },
  created () {
    this.$store.dispatch('getAllProducts')
  }
}
</script>

